<template>
  <el-menu-item index="4" @click="handleClick" class="menu-item">
    报告路况
  </el-menu-item>
  <report-popup v-model="dialogVisible" :position="position"></report-popup>
</template>

<script setup>
/*
    1,只能点击道路图层
        使用mapgis获取到关谷道路的数据，然后用turf判断道路图层是否包含当前点击的点
        如果包含，则显示实时路况的弹窗
        如果不包含，则alret提示 请点击道路
    2,弹窗的内容确定之后，传到服务器
*/

import { onMounted, getCurrentInstance } from 'vue'
import { createDraw } from '@/api/ol-api/createDraw.js'
import { Query } from '@/api/mapgis-api/Query'
import * as turf from '@turf/turf'
import ReportPopup from './ReportPopup.vue'
import { ref } from 'vue'
import { ElMessage } from 'element-plus'
const { proxy } = getCurrentInstance()
// 创建画布
const source = new ol.source.Vector({})
const layer = new ol.layer.Vector({
  source: source,
})

let service = {
  docName: 'guanggu',
  layerId: 1,
}

const position=ref([])
// 创建画笔
let draw = createDraw({
  type: 'Point',
  source,
  success: (e) => {
    const map = proxy.$map
     position.value = e.getGeometry().getCoordinates()
    Query.queryByLayerId(service).then((features) => {
      // 将道路数据转成geojson格式
      let line = new ol.format.GeoJSON().writeFeaturesObject(features)
      // 创建线的缓冲区，第二个参数是缓冲区的半径（单位是公里），缓冲区得用geojson格式
      const bufferedLine = turf.buffer(line, 0.2)

      // 将FeatureCollection转为Feature
      const bufferedLineFeature = bufferedLine.features.map((feature) => {
        return {
          type: 'Feature',
          properties: feature.properties,
          geometry: feature.geometry,
        }
      })

      // 判断当前点击的点是否在缓冲区内
      const point = turf.point(position.value)
      let isWithin = []
      bufferedLineFeature.map((feature) => {
        const result = turf.booleanPointInPolygon(point, feature) // 判断是否包含，只能使用geojson格式且type为Feature
        isWithin.push(result)
      })
      if (isWithin.some((item) => item === true)) {
        // 显示弹窗
        dialogVisible.value = true
      } else {
        ElMessage.error('请点击道路')
      }
    })
    // 结束画笔
    map.removeInteraction(draw)
  },
})

onMounted(() => {
  // 获取地图实例
  const map = proxy.$map
  // 添加道路图层
  map.addLayer(layer)
})
const dialogVisible = ref(false)
function handleClick() {
  const map = proxy.$map
  // 激活画笔
  map.addInteraction(draw)
}

</script>

<style scoped></style>
